package cn.com.demo.cms;

import cn.com.demo.cert.X509CertificateExample;
import cn.com.demo.keystore.JKSKeystoreExample;
import org.bouncycastle.cms.*;

import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.CertStore;
import java.security.cert.Certificate;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Iterator;

public class KeyTransEnvelopedDataExample {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        KeyStore store = JKSKeystoreExample.createKeyStore();
        PrivateKey priKey = (PrivateKey) store.getKey(X509CertificateExample.END_ALIAS, JKSKeystoreExample.password);
        Certificate[] chain = store.getCertificateChain(X509CertificateExample.END_ALIAS);

        CertStore certStore = CertStore.getInstance(
                "Collection", new CollectionCertStoreParameters(Arrays.asList(chain)), "BC");

        X509Certificate cert = (X509Certificate) chain[0];

        //set up the generator
        CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();
        gen.addKeyTransRecipient(cert);

        //create the enveloped-data object
        CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes());

        CMSEnvelopedData enveloped = gen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC, "BC");

        //re-create
        enveloped = new CMSEnvelopedData(enveloped.getEncoded());

        //look for our recipient identifier

        RecipientInformationStore recipients = enveloped.getRecipientInfos();

        Iterator i = recipients.getRecipients().iterator();
        if (i.hasNext()) {
            RecipientInformation recipient = (RecipientInformation) i.next();
            if (recipient != null) {
                //decrypt the data
                byte[] recData = recipient.getContent(priKey, "BC");

                //compare recovered data to the original data
                if (Arrays.equals((byte[]) data.getContent(), recData)) {
                    System.out.println("data recovery succeeded");
                } else
                    System.out.println("data recovery failed");
            } else {
                System.out.println("could not find a matching recipient");
            }
        }


    }

}
